from Bases import BaseObject
from bases import tree, widgets


class DeviceTree(BaseObject):
    def __init__(self, **kwargs):
        super(DeviceTree, self).__init__(**kwargs)
        self.col_names = kwargs.get('col_names')
        types = [str for x in self.col_names]
        self.col_types = kwargs.get('col_types', types)
        self.obj_names = kwargs.get('obj_names', [])
        self.base_dict = kwargs.get('base_dict')
        self.obj_name_attr = kwargs.get('obj_name_attr', 'saved_class_name')
        self.child_name_attr = kwargs.get('child_name_attr', 'saved_child_objects')
        if self.base_dict is None:
            self.base_dict = {'base':kwargs.get('base_obj')}
        
        self.col_attr_map = {}
        for key in self.col_names:
            self.col_attr_map.update({key:{}})
            for obj_key in self.obj_names:
                self.col_attr_map[key].update({obj_key:key})
        self.col_attr_map.update(kwargs.get('col_attr_map', {}))
        
        treekwargs = kwargs.copy()
        treekwargs.update(dict(base_dict=self.base_dict, obj_name_attr=self.obj_name_attr, child_name_attr=self.child_name_attr, 
                               column_names=self.col_names, column_types=self.col_types, 
                               column_attr_map=self.col_attr_map))
        self.tree = tree.GenericTreeStore(**treekwargs)
        
        if kwargs.get('build_widget', True):
            d = {}
            for key in ['used_columns', 'name']:
                d.setdefault(key, kwargs.get(key))
            d.update(kwargs.get('widget_kwargs', {}))
            self.widget = self.make_widget(**d)
            
    def make_widget(self, **kwargs):
        cls = kwargs.get('cls', widgets.Tree)
        used_cols = kwargs.get('used_columns')
        if not used_cols:
            used_cols = range(len(self.col_names))
        name = kwargs.get('name', '')
        col_dict = {}
        for col in used_cols:
            col_dict.update({col:self.col_names[col]})
        d = kwargs.copy()
        d.update(dict(name=name, model=self.tree, columns=col_dict))
        return cls(**d)
        
